package com.cqut.familiarity.service.impl;

import com.cqut.familiarity.service.RedisService;
import com.cqut.familiarity.utils.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 设置redis中的key、value
     * @param key
     * @param value
     * @return
     */
    @Override
    public ResultEntity setRedisKeyValueRemote(String key, String value) {
        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            return ResultEntity.ok();
        }catch (Exception e){
            e.printStackTrace();
            return ResultEntity.error().data("error",e.getMessage());
        }
    }

    /**
     * 指定redis中key、value的存储时长
     * @param key
     * @param value
     * @param time
     * @param timeUnit
     */
    @Override
    public ResultEntity setRedisKeyValueWithTimeout(String key, String value, long time, TimeUnit timeUnit) {
        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            operations.set(key, value, time, timeUnit);
            return ResultEntity.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error().data("error",e.getMessage());
        }
    }

    /**
     * 根据key获取value
     * @param key
     * @return
     */
    @Override
    public ResultEntity getRedisStringValueByKey(String key) {
        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();
            return ResultEntity.ok().data("key",operations.get(key));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error().data("error",e.getMessage());
        }
    }

    /**
     * 删除redis中的key
     * @param key
     * @return
     */
    @Override
    public ResultEntity removeRedisKey(String key) {
        try {
            redisTemplate.delete(key);
            return ResultEntity.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.error().data("error",e.getMessage());
        }
    }

}
